package com.xiaojun.whut.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.xiaojun.whut.Entity.CardMessage;
import com.xiaojun.whut.Entity.User;
import com.xiaojun.whut.Repository.CardMessageRepository;
import com.xiaojun.whut.Repository.UserRepository;
import com.xiaojun.whut.Service.PcUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @author 鲁佳磊
 * @create 2020-11-04 14:49
 */
@Service
public class PcUserSerivceImpl implements PcUserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CardMessageRepository cardMessageRepository;

    @Override
    public String updatePassword(String username, String oldpassword, String newpassword) {
        User byUserName = userRepository.findByUserName(username);
        String status = "200";
        if (!byUserName.getPassword().equals(oldpassword)) {
            status = "100";
            return status;
        }
        byUserName.setPassword(newpassword);
        userRepository.save(byUserName);
        return status;
    }

    @Override
    public String addCardInfo(String userName, String phoneNumber, String collage, String label, String descInfo) throws Exception {
        System.out.println("展示已经操作这个地方来了");

        CardMessage cardMessage = new CardMessage();
        cardMessage.setUserName(userName);
        cardMessage.setPhoneNumber(phoneNumber);
        cardMessage.setCollage(collage);
        cardMessage.setLabel(label);
        cardMessage.setContent(descInfo);
        cardMessage.setLikeNum(0);
        cardMessageRepository.save(cardMessage);            //保存这个信息
        return "200";
    }

    @Override
    public String getAllCardInfo(String label) throws Exception {

        List<CardMessage> allByLabel = cardMessageRepository.findAllByLabelOrderByCreateTimeDesc(label);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("flag",200);
        stringObjectHashMap.put("user",allByLabel);
        return JSON.toJSONString(stringObjectHashMap);
    }

    @Override
    public String updateLikeNum(int id, int likeNum) throws Exception {
        CardMessage byId = cardMessageRepository.findById(id);
        byId.setLikeNum(likeNum);
        cardMessageRepository.save(byId);
        return "200";
    }

    @Override
    public String getAllCardInfoMostNew(String label) throws Exception {
        List<CardMessage> allByLabel = cardMessageRepository.findAllByLabelOrderByLikeNumDesc(label);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("flag",200);
        stringObjectHashMap.put("user",allByLabel);
        return JSON.toJSONString(stringObjectHashMap);
    }
}
